# -*- coding: utf-8 -*-
import json
import glob
from flask import Flask, jsonify, request, make_response
from flask_restful import Api, Resource, reqparse
import os
import sys
import jsonschema
from flask_jsonschema_validator import JSONSchemaValidator

from redis_msg_type import RedisMsgType
from redisutils import RedisUtils

sys.path.append(os.path.dirname(sys.path[0]))
import utils.configloader as cfg
from logger import LOG

app = Flask(__name__)
api = Api(app)
JSONSchemaValidator(app=app, root='schemas')
app.config['JSON_SORT_KEYS'] = False
task_id = {}
redis_utils = RedisUtils(host=cfg.redis_host(), port=cfg.redis_port(),
                         )
redis_client = redis_utils.get_redis()


@app.errorhandler(jsonschema.ValidationError)
def deal_validation_error(e):
    """
    处理json的异常
    :param e:
    :return:
    """
    return jsonify(success=False, msg=e.args[0])


@app.route('/config', methods=['POST'])
def config():
    """
    修改配置文件
    :return:
    """
    json_body = request.json
    ip_addr = request.headers.get('X-Forwarded-For')
    if not ip_addr:
        ip_addr = ""
    LOG.info(ip_addr + 'is postting config')
    print(cfg.get_options('config'))
    licence = request.headers.get('license')
    if not licence:
        LOG.info(ip_addr + '未授权')
        return jsonify(success=False, msg="未授权")

    if licence != cfg.get_secret_key():
        LOG.info(ip_addr + '授权失败')

        return jsonify(success=False, msg="授权失败")
    set_time_msg = {}
    set_time_msg_flag = False
    options = cfg.get_options('config')
    for option, value in json_body.items():
        if option in options:
            if option == "work_time":
                set_time_msg_flag = True
                set_time_msg["work_time"] = value
            if option == "noon_sleep":
                set_time_msg_flag = True
                set_time_msg["noon_sleep"] = value
            if option == "break_off":
                set_time_msg_flag = True
                set_time_msg["break_off"] = value
            cfg.set_value(section='config', option=option, value=value)
        else:
            return jsonify(success=False, msg=option + ' not found,please check it!')
    cfg.save_change()
    LOG.info(ip_addr + '修改成功')
    msg = {
        "type": RedisMsgType.CONFIG.value,
        "data": json_body
    }
    try:
        redis_client.rpush(cfg.user_edit(), json.dumps(msg))
        redis_client.expire(cfg.user_edit(), cfg.expire_time())  # 设置过期时间
        if set_time_msg_flag:
            # 设置永不过期，等待scheduler获得到并修改成功之后删除。
            redis_client.set(cfg.set_time_edit(), json.dumps(set_time_msg, ensure_ascii=False))
    except Exception as e:
        LOG.error("write redis error ,the error is {}".format(e.args[0]))

    return jsonify(success=True, msg="修改成功")


@app.route('/monitorImages', methods=['GET'])
def get_monitor_images():
    """
    获取文件照片
    :return:
    """
    licence = request.headers.get('license')
    if not licence:
        return jsonify(success=False, msg="未授权")

    if licence != cfg.get_secret_key():
        return jsonify(success=False, msg="授权失败")

    camera_image_path = os.getcwd() + '/camera_images/'
    if not os.path.exists(camera_image_path):
        return jsonify(success=False, msg="未获取到摄像头图像")
    img_files = glob.glob(camera_image_path + '*.jpg')
    dataInfo = []
    for file in img_files:
        tmp_dict = {}

        (filepath, tempfilename) = os.path.split(file)
        (filename, extension) = os.path.splitext(tempfilename)
        tmp_dict['cameraNum'] = filename
        tmp_dict['img_path'] = file
        dataInfo.append(tmp_dict)

    return jsonify(success=True, msg='获取图片成功', dataInfo=dataInfo)


@app.route('/monitorPosition', methods=['POST'])
@app.validate('monitor', 'monitorPosition')
def get_monitor_position():
    """
    获取到员工信息，以及区域列表
    :return:
    """
    licence = request.headers.get('license')
    if not licence:
        return jsonify(success=False, msg="未授权")

    if licence != cfg.get_secret_key():
        return jsonify(success=False, msg="授权失败")

    instance = request.json  # 获取到请求信息

    results = {}
    staff_infos = instance.get('set_info')
    for staff in staff_infos:
        camera_num = staff.get('camera_num')
        try:
            x1 = int(staff.get('start_point').get('horizontal'))
            y1 = int(staff.get('start_point').get('vertical'))
            x2 = int(staff.get('end_point').get('horizontal'))
            y2 = int(staff.get('end_point').get('vertical'))
            w = x2 - x1
            h = y2 - y1
        except Exception as e:
            return jsonify(success=False, msg=e.args[0])
        if results.get(camera_num) is None:
            results[camera_num] = []
        if w <= 0:
            w = 100
        if h <= 0:
            h = 100
        results[camera_num].append({
            "staff_num": staff.get("staff_num"),
            "region_points": [x1, y1, w, h]
        })

    with open("config/staff_config.json", 'w') as f:
        json.dump(results, f, ensure_ascii=False)

    msg = {
        "type": RedisMsgType.COMMIT_STAFF_INFO.value,
        "data": results
    }
    redis_client.rpush(cfg.user_edit(), json.dumps(msg))
    redis_client.expire(cfg.user_edit(), cfg.expire_time())  # 设置过期时间
    return jsonify(success=True, msg="提交描点数据成功")


@app.route('/updateStaff', methods=['POST'])
@app.validate('staff', 'updateStaff')
def update_staff():
    """
    更新员工信息
    :return:
    """
    licence = request.headers.get('license')
    if not licence:
        return jsonify(success=False, msg="未授权")

    if licence != cfg.get_secret_key():
        return jsonify(success=False, msg="授权失败")

    instance = request.json  # 获取到请求信息
    image_id = instance.get('image_id')
    old_name = instance.get('staff_num')
    new_name = instance.get('update_num')

    with open('config/staff_config.json', 'r') as f:
        staff_infos = json.load(f)
        staff_info_in_one_camera = staff_infos.get(image_id)
        update_flag = False
        if staff_info_in_one_camera is not None:

            for staff in staff_info_in_one_camera:
                if staff.get('staff_num') == old_name:
                    update_flag = True
                    staff['staff_num'] = new_name
        else:
            return jsonify(success=False, msg="相机编号{0} not found".format(image_id))

        if not update_flag:
            return jsonify(success=False, msg="在相机编号为{0}的相机中没有找到名字为{1}的员工!请尝试添加!".format(image_id, old_name))
    with open('config/staff_config.json', 'w') as f:
        json.dump(staff_infos, f, ensure_ascii=False)

    msg = {
        "type": RedisMsgType.UPDATE_STAFF_INFO.value,
        "data": instance
    }
    redis_client.rpush(cfg.user_edit(), json.dumps(msg))
    redis_client.expire(cfg.user_edit(), cfg.expire_time())  # 设置过期时间
    return jsonify(success=True, msg="修改员工姓名成功！")


@app.route('/pics/<string:data>/<string:filename>', methods=['GET'])
def show_photo(filename,data):
    PATH = "detect_results/" + data + '/'
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(PATH + filename, "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png'
            return response
    else:
        pass


@app.route('/hello',methods=['GET'])
def hello_world():
    return "hello world"


if __name__ == '__main__':
    # p1 = mp.Process(target=web_app, args=())
    # p1.start()
    app.run(port=5555, debug=True)
